package fun.werfamily.wf.payment.core.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import fun.werfamily.wf.payment.core.domain.config.AlipayConfig;
import fun.werfamily.wf.payment.core.domain.constant.AlipayConstant;
import fun.werfamily.wf.payment.core.domain.dto.req.PayCancelReq;
import fun.werfamily.wf.payment.core.domain.dto.req.PayCreateReq;
import fun.werfamily.wf.payment.core.domain.dto.resp.AlipayNotifyResp;
import fun.werfamily.wf.payment.core.domain.dto.resp.PayCancelSuccessRespDTO;
import fun.werfamily.wf.payment.core.domain.dto.resp.PaySuccessRespDTO;
import fun.werfamily.wf.payment.core.domain.enums.PayStatusEnum;
import fun.werfamily.wf.payment.core.domain.exception.PaymentCoreException;
import fun.werfamily.wf.payment.core.domain.exception.ResponseCodeEnum;
import fun.werfamily.wf.payment.core.domain.service.PaymentBaseAbstractService;
import fun.werfamily.wf.payment.core.domain.util.OrderNoGenUtil;
import fun.werfamily.wf.payment.core.infrastructure.dataobject.PayDO;
import fun.werfamily.wf.payment.core.infrastructure.mapper.PayMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Mr.WenMing Zhang
 * @Date: 2023-05-02 20:13
 * @Description:
 */
@Service
@Slf4j
public class AliPayService extends PaymentBaseAbstractService {

    @Resource
    private PayMapper payMapper;

    @Override
    public PaySuccessRespDTO doPay(PayCreateReq req) {
        // TODO 加同步锁
        // 订单支付状态校验

        PaySuccessRespDTO paySuccessRespDTO = new PaySuccessRespDTO();
        String alipayForm = getAlipayForm(req);
        if (StringUtils.isBlank(alipayForm)) {
            throw new PaymentCoreException(ResponseCodeEnum.PAY_ERROR);
        }
        paySuccessRespDTO.setForm(alipayForm);
        // 保存支付流水
        PayDO payDO = new PayDO();
        payDO.setPayNo(OrderNoGenUtil.getOrderNo());
        payDO.setPayAmount(req.getPayAmount());
        payDO.setBizNo(req.getBizNo());
        payDO.setBizType(req.getBizType());
        payDO.setPayType("AILI_PAY_H5");
        payDO.setPayTime(req.getPayTime());
        payDO.setPayStatus(PayStatusEnum.WAIT_PAY.getPayStatus());
        payDO.setCreateBy(req.getCreateBy());
        payDO.setUpdateBy(req.getCreateBy());
        payMapper.insertSelective(payDO);
        paySuccessRespDTO.setPayNo(payDO.getPayNo());
        return paySuccessRespDTO;
    }

    @Override
    public void postCheck(PayCreateReq req) {

    }


    private String getAlipayForm(PayCreateReq req) {
        if (req.getBizNo() != null) {
            // 商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = req.getBizNo();
            // 订单名称，必填
            String subject = req.getBizNo();
            // 付款金额，必填
            String total_amount = req.getPayAmount().toString();
            // 商品描述，可空
            String body = null;
            // 超时时间 可空
            String timeout_express = "2m";
            // 销售产品码 必填
            String product_code = "QUICK_WAP_WAY";
            /**********************/
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.GATEWAY_URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

            // 封装请求支付信息
            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(out_trade_no);
            model.setSubject(subject);
            model.setTotalAmount(total_amount);
            model.setBody(body);
            model.setTimeoutExpress(timeout_express);
            model.setProductCode(product_code);
            alipay_request.setBizModel(model);
            // 设置异步通知地址
            alipay_request.setNotifyUrl(AlipayConfig.notify_url);
            // 设置同步地址
            alipay_request.setReturnUrl(AlipayConfig.return_url);
            // form表单生产
            String form = "";
            try {
                // 调用SDK生成表单
                form = client.pageExecute(alipay_request).getBody();
            } catch (AlipayApiException e) {
                log.error("支付失败req{}", req, e);
            }
            return form;
        }
        return null;
    }

    @Override
    public PayCancelSuccessRespDTO cancelPay(PayCancelReq req) {
        // TODO 加同步锁

        return null;
    }

    /**
     * 1.一定要验签，防止黑客篡改参数
     * 实际验证过程建议商户务必添加以下校验：
     * 1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
     * 2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
     * 3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
     * 4、验证app_id是否为该商户本身。
     *
     * @param request
     */
    @Override
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        log.error("****************************支付宝回调*************************************");
        Map<String, String> params = getParams(request);
        log.info("-----------params----------{}", JSON.toJSONString(params));
        //调用SDK验证签名
        boolean signVerified;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
        } catch (AlipayApiException e) {
            log.error("验签异常，", e);
            throw new RuntimeException(e);
        }
        if (signVerified) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.putAll(params);
            AlipayNotifyResp alipayNotifyResp = jsonObject.toJavaObject(AlipayNotifyResp.class);
            // TRADE_SUCCESS(表示交易已经成功结束，可以对该交易做后续操作，如：分润、退款等);
            try {
                if (AlipayConstant.PAY_SUCCESS.equals(alipayNotifyResp.getTradeStatus())) {
                    // 1.mq通知订单
                    // 2.更改支付状态
                    //支付成功发送通知给支付宝
                    response.getWriter().print("success");
                    response.getWriter().flush();
                }
                response.getWriter().print("fail");
                response.getWriter().flush();
            } catch (Exception e) {
                log.error("支付宝回调异常", e);
            }
        }
    }

    @Override
    public String getPayStatus(String orderNo) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.GATEWAY_URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
        //商户订单号，商户网站订单系统中唯一订单号
        //String out_trade_no = new String(request.getParameter("WIDTQout_trade_no").getBytes("UTF-8"),"UTF-8");
        //支付宝交易号
        //String trade_no = new String(request.getParameter("WIDTQtrade_no").getBytes("UTF-8"),"UTF-8");
        //请二选一设置
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNo + "\"}");
        AlipayTradeQueryResponse alipayResponse = null;
        try {
            alipayResponse = alipayClient.execute(alipayRequest);
        } catch (Exception e) {
            log.error("调用支付宝获取交易状态异常order={}", orderNo, e);
        }
        //获取支付宝交易状态
        String tradeState = alipayResponse.getTradeStatus();
        log.info("支付宝交易状态:{}", tradeState);
        return tradeState;
    }

    /**
     * 获取支付宝回调参数
     *
     * @param request
     * @return
     */
    private Map<String, String> getParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("UTF-8"), "utf-8");
            } catch (Exception e) {
                log.error("支付宝回调，参数解析异常", e);
            }
            params.put(name, valueStr);
        }
        return params;
    }
}
